package com.interview.ujiuye2;

/**
 * Copyright (C), 2018-2020
 * FileName: SingleDemo
 * Author:   kongfanyu
 * Date:     2020/10/10 09:45
 */
public class SingletonDemo {

    //3.添加一个自身的引用对象, volatile禁止指令重排，返回完整的初始化之后的对象
    private volatile static SingletonDemo instance;

    //1.构造方法私有化
    private SingletonDemo(){
        System.out.println("===创建SingletonDemo对象===");
    }

    //2.创建一个公有的、静态的、获取自身实例的方法

    public static SingletonDemo getInstance(){
        if (instance == null){
            synchronized (SingletonDemo.class) {
                if (instance == null){
                    instance = new SingletonDemo();//创建对象
                }

            }
        }
        return instance;
    }

    public static void main(String[] args) {
        for (int i=0;i<10; i++){
            new Thread(
                    new Runnable() {
                        @Override
                        public void run() {
                            System.out.println(SingletonDemo.getInstance() == SingletonDemo.getInstance()  );
                            System.out.println(SingletonDemo.getInstance() == SingletonDemo.getInstance()  );
                            System.out.println(SingletonDemo.getInstance() == SingletonDemo.getInstance()  );
                        }
                    }
            ).start();
        }

    }

    private static void test1() {
        System.out.println(SingletonDemo.getInstance() == SingletonDemo.getInstance()  );
        System.out.println(SingletonDemo.getInstance() == SingletonDemo.getInstance()  );
        System.out.println(SingletonDemo.getInstance() == SingletonDemo.getInstance()  );
        System.out.println(SingletonDemo.getInstance() == SingletonDemo.getInstance()  );
    }
}
